package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.YearReport;
import com.hulman.oms.bean.User;
import com.hulman.oms.dao.YearReportDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.DocUtil;
import com.hulman.oms.util.FileUtil;
import com.hulman.oms.util.StringUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.Year;
import java.time.ZoneId;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class YearReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private YearReportDao yearReportDao;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<YearReport> findYearReports(Map<String, Object> map)
    {
        return yearReportDao.findYearReports(map);
    }

    public Integer findYearReportsCount(Map<String, Object> map)
    {
        return yearReportDao.findYearReportsCount(map);
    }

    public Result findYearReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = yearReportDao.findYearReportsCount(map);
        List<YearReport> data = yearReportDao.findYearReports(map);
        return new Result(data, count);
    }

    public YearReport findYearReportById(Integer id)
    {
        return yearReportDao.findYearReportById(id);
    }

    public void saveYearReport(YearReport yearReport)
    {
        if (yearReport.getId() != null && yearReport.getId() != 0)
        {
            yearReportDao.updateYearReport(yearReport);
        } else
        {
            yearReportDao.insertYearReport(yearReport);
        }
    }

    public void deleteYearReportById(Integer id)
    {
        yearReportDao.deleteYearReportById(id);
    }

    public void deleteYearReports(int[] ids)
    {
        yearReportDao.deleteYearReports(ids);
    }

    /**
     * 检查工作报告是否已生成
     *
     * @param yearReport
     */
    public void checkYearReport(YearReport yearReport)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("year", yearReport.getYear());
        Integer count = yearReportDao.findYearReportsCount(map);
        if (count > 0)
        {
            throw new IoTException("该年度工作报告已生成");
        }
    }

    public void create(YearReport yearReport) throws IOException
    {
        checkYearReport(yearReport);
        User user = SubjectUtil.getUser();
        yearReport.setCreateById(user.getId());
        yearReport.setCreateByName(user.getName());
        int year = yearReport.getYear();
        LocalDate firstDay = LocalDate.of(year, 1, 1);
        LocalDate lastDay = Year.of(year).atMonth(12).atEndOfMonth();
        Date startDate = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        yearReport.setStartDate(startDate);
        yearReport.setEndDate(endDate);
        yearReport.setState(0);
        //模板生成报告
        if (yearReport.getSource() == 1)
        {
            Map<String, Object> map = new HashMap<>();
            map.put("reportCycle", yearReport.getReportCycle());
            InputStream inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("template/year-report.docx");
            String fileId = StringUtil.uuid() + ".docx";
            Path filePath = Paths.get(fileHome, fileId);
            OutputStream outputStream = Files.newOutputStream(filePath);
            DocUtil.export(inputStream, outputStream, map);
            yearReport.setFileId(fileId);
        }
        yearReportDao.insertYearReport(yearReport);
        String fileName = yearReport.getReportCycle() + "养护年报." + FileUtil.parseExtName(yearReport.getFileId());
        onlyOfficeService.create(yearReport.getFileId(), fileName);
    }

    public void submit(Integer id)
    {
        YearReport yearReport = yearReportDao.findYearReportById(id);
        yearReport.setState(1);
        yearReport.setEditDate(new Date());
        yearReportDao.updateYearReport(yearReport);
    }

}
